﻿using System;
using System.Linq;
using Markdig;
using NPoco;
using YYBlog.Core.Entity;
using YYBlog.Core.Extensions;

namespace YYBlog.Core.Commands.Posts
{
	public class NewPostCommand
	{
		public Author Author { get; set; }

		public string Title { get; set; }

		public string TitleSlug { get; set; }

		public string MarkDown { get; set; }

		public string Tags { get; set; }

		public DateTime PubDate { get; set; }

		public bool Published { get; set; }
	}

	public class NewPostCommandInvoker : ICommandInvoker<NewPostCommand, CommandResult>
	{
		private readonly Database _db;

		public NewPostCommandInvoker(Database db)
		{
			_db = db;
		}

		public CommandResult Execute(NewPostCommand command)
		{
			var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
			//TODO:应该验证TitleSlug是否唯一
			var post = new BlogPost
			{
				AuthorEmail = command.Author.Email,
				AuthorDisplayName = command.Author.DisplayName,
				MarkDown = command.MarkDown,
				Content = Markdown.ToHtml(command.MarkDown, pipeline),
				PubDate = command.PubDate,
				Status = command.Published ? PublishStatus.Published : PublishStatus.Draft,
				Title = command.Title,
				TitleSlug = command.TitleSlug.IsNullOrWhitespace() ? command.Title.Trim().ToSlug() : command.TitleSlug.Trim().ToSlug()
				,AuthorId=command.Author.Id
			};
			if (!command.Tags.IsNullOrWhitespace())
			{
				var tags = command.Tags.Trim().Split(',').Select(s => s.Trim());
				post.Tags = string.Join(",", tags.Select(p => p.ToSlug()));
                foreach (var tag in tags)
				{
					var slug = tag.ToSlug();
					var tagEntry = _db.SingleOrDefaultById<Tag>(slug);
					if (tagEntry == null)
					{
						tagEntry = new Tag
						{
							Slug = slug,
							Name = tag,
							PostCount = 1
						};
						_db.Insert(tagEntry);
					}
					else
					{
						tagEntry.PostCount++;
						_db.Update(tagEntry);
					}
				}
			}
			else
				post.Tags =string.Empty;

			var result = _db.Insert(post);

			return CommandResult.SuccessResult;
		}
	}
}